package top.kaoshanji.p1ch04a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

/**
 * 代码清单-p1ch04a-92页a：查询服务器信息
 * URL访问地址：/serverSnoop
 * @author kaoshanji
 * ^_^
 * create time 2025/4/3 17:11
 */
public class ServerSnoop extends GenericServlet {

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        res.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = res.getWriter();

        ServletContext context = getServletContext();

        out.println("req.getServerName(): " + req.getServerName());

        out.println("req.getServerPort(): " + req.getServerPort());
        out.println("context.getServerInfo(): " + context.getServerInfo());
        out.println("getServerInfo name: " + getServerInfoName(context.getServerInfo()));
        out.println("getServerInfo version: " + getServerInfoVersion(context.getServerInfo()));

        out.println("context.getAttributeNames(): ");
        Enumeration<String> enumeration = context.getAttributeNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            out.println("  context.getAttribute(\"" + name + "\"): " + context.getAttribute(name));
        }

    }

    private String getServerInfoName(String serverInfo) {
        int slash = serverInfo.indexOf('/');
        if (slash == -1) {
            return serverInfo;
        } else {
            return serverInfo.substring(0, slash);
        }
    }

    private String getServerInfoVersion(String serverInfo) {
        // 在斜线和空格之间是版本信息
        int slash = serverInfo.indexOf('/');
        if (slash == -1) {
            return null;
        }
        int space = serverInfo.indexOf(' ', slash);
        if (space == -1) {
            space = serverInfo.length();
        }

        return serverInfo.substring(slash + 1, space);
    }

}
